package comgutianyu.qihangjiaoyu.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import comgutianyu.qihangjiaoyu.MainActivity;
import comgutianyu.qihangjiaoyu.R;
import comgutianyu.qihangjiaoyu.db.UserDao;
import comgutianyu.qihangjiaoyu.model.User;

public class PersonalInfoActivity extends AppCompatActivity implements View.OnClickListener {
    private UserDao userDao;
    private TextView tvNickname, tvUsername, tvPhone, tvGender, tvExamIntent;
    private User currentUser;
    private View layoutNickname, layoutPhone, layoutGender, layoutExamIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_info);

        userDao = new UserDao(this);
        initViews();
        loadUserData();

        ImageButton btnBack = findViewById(R.id.btnBack);
        btnBack.setOnClickListener(v -> onBackPressed());
    }

    @Override
    public void onBackPressed() {
        // 检查是否是从MainActivity启动的
        super.onBackPressed();
        if (isTaskRoot()) {
            // 如果是根Activity，启动MainActivity
            startActivity(new Intent(this, MainActivity.class));
        }
        finish();
    }

    private void initViews() {
        tvNickname = findViewById(R.id.tvNickname);
        tvUsername = findViewById(R.id.tvUsername);
        tvPhone = findViewById(R.id.tvPhone);
        tvGender = findViewById(R.id.tvGender);
        tvExamIntent = findViewById(R.id.tvExamIntent);

        // 获取布局引用并设置点击事件
        layoutNickname = findViewById(R.id.layoutNickname);
        View layoutUsername = findViewById(R.id.layoutUsername);
        layoutPhone = findViewById(R.id.layoutPhone);
        layoutGender = findViewById(R.id.layoutGender);
        layoutExamIntent = findViewById(R.id.layoutExamIntent);

        layoutNickname.setOnClickListener(this);
        layoutUsername.setOnClickListener(this);
        layoutPhone.setOnClickListener(this);
        layoutGender.setOnClickListener(this);
        layoutExamIntent.setOnClickListener(this);

        Button btnLogout = findViewById(R.id.btnLogout);
        btnLogout.setOnClickListener(v -> showLogoutDialog());
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.layoutNickname) {
            showEditDialog("修改昵称", tvNickname.getText().toString(), "nickname");
        } else if (v.getId() == R.id.layoutUsername) {
            showUsernameDialog();
        } else if (v.getId() == R.id.layoutPhone) {
            showEditDialog("修改手机号", tvPhone.getText().toString(), "phone");
        } else if (v.getId() == R.id.layoutGender) {
            showGenderDialog();
        } else if (v.getId() == R.id.layoutExamIntent) {
            showExamIntentionDialog();
        }
    }

    private void showEditDialog(String title, String currentValue, final String field) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.CustomAlertDialog);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null);
        final EditText editText = view.findViewById(R.id.editText);
        editText.setText(currentValue);
        editText.setHint("请输入" + title.substring(2));

        AlertDialog dialog = builder.setTitle(title)
                .setView(view)
                .setPositiveButton("确定", null)  // 先设置为null
                .setNegativeButton("取消", null)
                .create();

        dialog.show();

        // 获取对话框按钮并设置点击事件
        dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(v -> {
            String newValue = editText.getText().toString().trim();
            if (!newValue.isEmpty()) {
                updateUserField(field, newValue);
                dialog.dismiss();
            } else {
                editText.setError("内容不能为空");
            }
        });
    }

    private void showGenderDialog() {
        final String[] genders = {"男", "女", "未设置"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.CustomAlertDialog);
        builder.setTitle("选择性别")
                .setItems(genders, (dialog, which) -> {
                    String selectedGender = genders[which];
                    updateUserField("gender", selectedGender);
                })
                .show();
    }

    private void showExamIntentionDialog() {
        final String[] examIntentions = {"四六级", "考研", "雅思托福"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.CustomAlertDialog);
        builder.setTitle("选择备考意向")
                .setItems(examIntentions, (dialog, which) -> {
                    String selectedIntent = examIntentions[which];
                    updateUserField("exam_intention", selectedIntent);
                })
                .show();
    }

    private void updateUserField(String field, String value) {
        if (currentUser != null) {
            switch (field) {
                case "nickname":
                    currentUser.setNickname(value);
                    tvNickname.setText(value);
                    break;
                case "phone":
                    if (isValidPhoneNumber(value)) {
                        // 检查新手机号是否已被使用
                        User existingUser = userDao.getUserByPhone(value);
                        if (existingUser != null && existingUser.getId() != currentUser.getId()) {
                            Toast.makeText(this, "该手机号已被使用", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        currentUser.setPhone(value);
                        tvPhone.setText(value);
                        // 更新SharedPreferences中保存的手机号
                        getSharedPreferences("user_prefs", MODE_PRIVATE)
                                .edit()
                                .putString("current_phone", value)
                                .apply();
                    } else {
                        Toast.makeText(this, "请输入有效的手机号", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    break;
                case "gender":
                    currentUser.setGender(value);
                    tvGender.setText(value);
                    break;
                case "exam_intention":
                    currentUser.setExamIntention(value);
                    tvExamIntent.setText(value);
                    break;
            }

            // 更新数据库
            int result = userDao.updateUser(currentUser);
            if (result > 0) {
                Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "修改失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private boolean isValidPhoneNumber(String phone) {
        return phone.matches("^1[3-9]\\d{9}$");
    }

    private void loadUserData() {
        // 从SharedPreferences获取当前登录用户的手机号
        String currentPhone = getSharedPreferences("user_prefs", MODE_PRIVATE)
                .getString("current_phone", null);
        
        if (currentPhone == null) {
            // 如果没有登录信息，跳转到登录界面
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
            return;
        }

        // 通过手机号查询用户信息
        currentUser = userDao.getUserByPhone(currentPhone);
        
        if (currentUser != null) {
            // 显示用户信息
            tvNickname.setText(currentUser.getNickname());
            tvUsername.setText(currentUser.getUsername());
            tvPhone.setText(currentUser.getPhone());
            tvGender.setText(currentUser.getGender());
            tvExamIntent.setText(currentUser.getExamIntention());
        } else {
            // 如果查询不到用户信息，也跳转到登录界面
            getSharedPreferences("user_prefs", MODE_PRIVATE)
                    .edit()
                    .clear()
                    .apply();
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    private void showUsernameDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.CustomAlertDialog);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null);
        final EditText editText = view.findViewById(R.id.editText);
        editText.setText(tvUsername.getText().toString());
        editText.setHint("请输入新的用户名");

        AlertDialog dialog = builder.setTitle("修改用户名")
                .setView(view)
                .setPositiveButton("确定", null)
                .setNegativeButton("取消", null)
                .create();

        dialog.show();

        dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(v -> {
            String newUsername = editText.getText().toString().trim();
            if (!newUsername.isEmpty()) {
                if (isValidUsername(newUsername)) {
                    updateUsername(newUsername);
                    dialog.dismiss();
                } else {
                    editText.setError("用户名只能包含字母、数字���下划线");
                }
            } else {
                editText.setError("用户名不能为空");
            }
        });
    }

    private boolean isValidUsername(String username) {
        return username.matches("^[a-zA-Z0-9_]{4,16}$");
    }

    private void updateUsername(String newUsername) {
        User existingUser = userDao.getUserByUsername(newUsername);
        if (existingUser != null) {
            Toast.makeText(this, "该用户名已被使用", Toast.LENGTH_SHORT).show();
            return;
        }

        String oldUsername = currentUser.getUsername();
        
        currentUser.setUsername(newUsername);
        
        userDao.deleteUser(oldUsername);
        
        long result = userDao.insertUser(currentUser);
        
        if (result > 0) {
            tvUsername.setText(newUsername);
            Toast.makeText(this, "用户名修改成功", Toast.LENGTH_SHORT).show();
        } else {
            currentUser.setUsername(oldUsername);
            Toast.makeText(this, "用户名修改失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void showLogoutDialog() {
        new AlertDialog.Builder(this, R.style.CustomAlertDialog)
                .setTitle("退出登录")
                .setMessage("确定要退出登录吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    logout();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void logout() {
        // 清除登录状态
        getSharedPreferences("user_prefs", MODE_PRIVATE)
                .edit()
                .clear()
                .apply();

        // 跳转到登录界面
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }
} 